/*eslint-disable*/
import Vue from 'vue';
import Router from 'vue-router';
import beforeEachRoute from './guards';
import routes from './routes';

Vue.use(Router);

const scrollBehavior = (to, from, savedPosition) => {
  // SavedPosition is only available for popstate navigations.
  if (savedPosition) {
    return savedPosition;
  } else {
    let position = {};
    // If no children detected
    if (to.matched.length < 2) {
      // Scroll to the top of the page
      position = { x: 0, y: 0 };
    } else if (to.matched.some(r => r.components.default.scrollToTop)) {
      // If one of the children has scrollToTop option set to true
      position = { x: 0, y: 0 };
    }
    // If link has anchor, scroll to anchor by returning the selector
    if (to.hash) {
      position = { selector: to.hash };
    }
    return position;
  }
};

// 路由插件处理
function createRouter() {
  const router = new Router({
    mode: 'history',
    base: '/',
    linkActiveClass: 'b-link-active',
    linkExactActiveClass: 'b-c-link-active',
    scrollBehavior,
    routes,
  });

  beforeEachRoute(router);

  return router;
}

export default createRouter();
